package com.adams.app.ui;

import java.util.ArrayList;
import java.util.Random;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.sharesdk.onekeyshare.OnekeyShare;

import com.adams.app.AppData;
import com.adams.app.R;
import com.adams.app.common.Global;
import com.adams.app.listener.MySearchListener;
import com.adams.app.model.Search;
import com.adams.app.utils.MapUtils;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.search.MKPoiInfo;
import com.baidu.mapapi.search.MKSearch;
import com.baidu.mapapi.utils.DistanceUtil;

public class NearbyActivity extends ActionBarActivity {

	private LinearLayout nearbyLayout;
	private MKSearch mkSearch;
	private AppData application;
	private LocationClient mLocationClient;
	private BDLocation local;
	private BMapManager mBMapMan;
	private String flag;
	private Search[] searhList;
	private LinearLayout contentView;
	private LinearLayout nearLoading;
	
	private Handler handler = new Handler() {

		@SuppressWarnings("unchecked")
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			switch (msg.what) {
			case Global.WHAT1:
				Log.i("TEST", "1");

				convertToSearchList((ArrayList<MKPoiInfo>) msg.obj);
				sortByDistance();

				if (searhList != null && searhList.length != 0) {
					contentView.setVisibility(View.VISIBLE);
					nearLoading.setVisibility(View.GONE);
					int len = searhList.length;
					if (flag.equals(Global.SHAKE_FLAG)) {
						Random random = new Random();
						int index = random.nextInt(len);
						View childView = getView(searhList[index]);
						childView.findViewById(R.id.neary_info).setVisibility(
								View.VISIBLE);
						childView.setOnClickListener(itemClickListener);
						nearbyLayout.addView(childView);
					} else {
						for (int i = 0; i < len; i++) {
							Search search = searhList[i];
							View childView = getView(search);
							childView.setOnClickListener(itemClickListener);
							nearbyLayout.addView(childView);
						}
					}
				} else {
					Toast.makeText(NearbyActivity.this, "没有找到", 1).show();
				}
				break;
			default:
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_nearby);

		initViews();
		loadData();
		bindData();
	}

	private void bindData() {

	}

	private void loadData() {
		flag = getIntent().getStringExtra(Global.FLAG);
		application = (AppData) getApplication();
		mBMapMan = application.getBmManager();
		mBMapMan.start();
		mLocationClient = application.getLocationClient();
		local = mLocationClient.getLastKnownLocation();
		mkSearch = application.getSearch();

		AppData.flag = Global.FOOD_NAME;
		mkSearch.init(application.getMapManager(),
				new MySearchListener(handler));
		mkSearch.poiSearchNearBy(Global.SERACH_NAME,
				MapUtils.getGeoPoint(local), 100000);

	}

	private void initViews() {
		ActionBar actionBar = getSupportActionBar();
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
		nearbyLayout = (LinearLayout) this.findViewById(R.id.layout_nearbylist);
		contentView = (LinearLayout) this.findViewById(R.id.nearby_content);
		nearLoading = (LinearLayout) this.findViewById(R.id.neary_loading);
	}

	/**
	 * 
	 * @description 绑定详细信息到View
	 * 
	 * @author ChengBin
	 * @date 2014年1月2日上午11:33:32
	 * @param search
	 * @return
	 */
	private View getView(Search search) {
		View v = LayoutInflater.from(this).inflate(R.layout.item_vendor_map,
				null);
		TextView nameText = (TextView) v.findViewById(R.id.tvName);
		// TextView priceText = (TextView) v.findViewById(R.id.tvPrice);
		TextView categoryText = (TextView) v.findViewById(R.id.tvCategory);
		TextView addressText = (TextView) v.findViewById(R.id.tvAddress);
		TextView distanceText = (TextView) v.findViewById(R.id.tvDistance);
		TextView daohangText = (TextView) v.findViewById(R.id.daohang);
		TextView zufanjuText = (TextView) v.findViewById(R.id.zufanju);
		TextView bohaoText = (TextView) v.findViewById(R.id.bohao);
		TextView fenxiangText = (TextView) v.findViewById(R.id.fenxiang);

		daohangText.setTag(search);
		bohaoText.setTag(search.phone);
		fenxiangText.setTag(search);
		zufanjuText.setTag(search);

		nameText.setText(search.name);
		// priceText.setText(mkPoiInfo.);
		// categoryText.setText(mkPoiInfo.ePoiType);
		addressText.setText(search.address);
		distanceText.setText(search.distance + "米");

		daohangText.setOnClickListener(daohangListener);
		zufanjuText.setOnClickListener(zufanjuListener);
		bohaoText.setOnClickListener(bohaoListener);
		fenxiangText.setOnClickListener(fenxiangListener);

		return v;
	}

	/**
	 * 
	 * @description 返回
	 * 
	 * @author ChengBin
	 * @date 2014年1月8日下午4:00:53
	 * @param list
	 * @return
	 */
	private void convertToSearchList(ArrayList<MKPoiInfo> list) {
		MKPoiInfo mkPoiInfo;
		int len = list.size();
		searhList = new Search[len];
		for (int i = 0; i < len; i++) {
			mkPoiInfo = list.get(i);
			Search search = new Search();
			search.distance = (int) DistanceUtil.getDistance(
					MapUtils.getGeoPoint(local), mkPoiInfo.pt);
			search.name = mkPoiInfo.name;
			search.address = mkPoiInfo.address;
			search.phone = mkPoiInfo.phoneNum;
			searhList[i] = search;
		}
	}

	/***
	 * 
	 * @description 按距离排序
	 * 
	 * @author ChengBin
	 * @date 2014年1月8日下午4:13:29
	 */
	private void sortByDistance() {
		int size = searhList.length;
		boolean flag = true;
		Search search;
		if (size != 0) {
			for (int i = 0; i < size - 1; i++) {
				for (int j = 0; j < size - i - 1; j++) {
					if (searhList[j].distance >= searhList[j + 1].distance) {
						search = searhList[j];
						searhList[j] = searhList[j + 1];
						searhList[j + 1] = search;
						flag = false;
					}
				}
				if (flag) {
					break;
				}
			}
		}
	}

	OnClickListener itemClickListener = new OnClickListener() {
		public void onClick(View view) {
			LinearLayout layout = (LinearLayout) view
					.findViewById(R.id.neary_info);

			if (layout.getVisibility() == View.GONE) {
				layout.setVisibility(View.VISIBLE);
			} else {
				layout.setVisibility(View.GONE);
			}
		}
	};

	OnClickListener daohangListener = new OnClickListener() {
		public void onClick(View v) {
			Search search = (Search) v.getTag();
			if (search != null && !"".equals(search.address.trim())) {
				Intent intent = new Intent(NearbyActivity.this,
						MyMapActivity.class);
				intent.putExtra(Global.ADDRESS, search.address);
				intent.putExtra(Global.NAME, search.name);
				startActivity(intent);
			}
		}
	};
	OnClickListener zufanjuListener = new OnClickListener() {
		public void onClick(View v) {
			Search search = (Search) v.getTag();
			String info = "饭局喜讯:【" + search.name + "】,位置在" + search.address
					+ ",餐厅电话：" + search.phone + "。此短信由#玩转广元#系统编辑发送!";
			if (info != null && !"".equals(info.trim())) {
				Intent it = new Intent(Intent.ACTION_VIEW);
				it.putExtra("sms_body", info);
				it.setType("vnd.android-dir/mms-sms");
				startActivity(it);
			}
		}
	};

	OnClickListener bohaoListener = new OnClickListener() {
		public void onClick(View v) {
			String tel = v.getTag().toString();
			if (tel == null || "".equals(tel.trim())) {
				Toast.makeText(NearbyActivity.this, "对不起，暂无电话号码",
						Toast.LENGTH_SHORT).show();
				return;
			}
			String[] tels = tel.split(",");
			if (tels.length != 0) {
				Intent intent = new Intent(Intent.ACTION_DIAL,
						Uri.parse("tel://" + tels[0]));
				startActivity(intent);
			} else {
				Toast.makeText(NearbyActivity.this, "对不起，暂无电话号码",
						Toast.LENGTH_SHORT).show();
			}
		}
	};

	OnClickListener fenxiangListener = new OnClickListener() {
		public void onClick(View v) {
			Search search = (Search) v.getTag();

			// 快捷分享
			OnekeyShare oks = new OnekeyShare();
			oks.setNotification(R.drawable.ic_launcher, "Gtpass");
			String info = "刚刚发现#"+search.name+"#，推荐吃货们去试试哟。地址："+search.address+"；电话："+search.phone+"。【餐厅分享来自玩转广元 】";
			oks.setText(info);
			oks.setSilent(false);
			oks.show(NearbyActivity.this);
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		// 退出时销毁定位
		if (mLocationClient != null)
			mLocationClient.stop();

		if (mkSearch != null) {
			mkSearch.destory();
			mkSearch = null;
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mBMapMan != null) {
			mBMapMan.stop();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mBMapMan != null) {
			mBMapMan.start();
		}
	}

}
